<template>
  <div class="app-container">
    <!--工具栏-->
    <div v-show="!vShow" class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">设备名称</label>
        <el-input v-model="query.name" clearable placeholder="设备名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="设备编号" prop="no">
            <el-input v-model="form.no" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="所属公司" prop="'dept.id'">
            <treeselect
                v-model="form.dept.id"
                :options="depts"
                :load-options="loadDepts"
                style="width: 178px"
                placeholder="选择部门"
              />
            <!-- <el-input v-model="form.deptId" style="width: 370px;" /> -->
          </el-form-item>
          <el-form-item label="设备类型" prop="type">
            <el-input v-model="form.type" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="设备地址">
            <el-input v-model="form.address" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="no" label="设备编号" />
        <el-table-column prop="name" label="设备名称" />
        <el-table-column :show-overflow-tooltip="true" prop="dept" label="所属公司">
            <template slot-scope="scope">
              <div>{{ scope.row.dept&& scope.row.dept.name }}</div>
            </template>
          </el-table-column>
        <el-table-column prop="type" label="设备类型" />
        <el-table-column prop="address" label="设备地址" />
        <el-table-column label="视频" width="150px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="play(1, scope.row)">直播</el-button>
            <el-button size="mini" type="primary" @click="play(2, scope.row)">视频</el-button>
          </template>
        </el-table-column>

        <el-table-column v-permission="['admin','device:edit','device:del']" label="操作" width="150px">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
           </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <div v-show="vShow" class="liveBox">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>{{vtype==1 ?'直播' : '视频'}}</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="close">关闭</el-button>
        </div>
        <div style="margin: 0 auto;" v-if="vtype==1">
          <video id="videoElement" style="display: block;" width="800px"></video>
        </div>
        <div style="margin: 0 auto;" v-else class="vBox">
          <div v-if="vList.length==0" style="width: 100%;text-align: center; margin: 50px 0;">暂无数据</div>
          <video v-else controls class="vv" v-for="i in vList" :id="'v'+i.id" :key="i.id" style="display: block;" width="200px"></video>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import flvjs from "flv.js"
import { getDepts, getDeptsAll } from '@/api/system/dept'
import { deviceVideo } from '@/api/system/device'

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

import crudDevice from '@/api/system/device'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
const defaultForm = { dept: { id: null, name: '测试部' }, id: null, no: null, name: null, deptId: null, type: null, address: null }
export default {
  name: 'Device',
  components: { Treeselect, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '设备', url: 'api/device', idField: 'id', sort: 'id,desc', crudMethod: { ...crudDevice }})
  },
  data() {
    return {
      vShow: false,
      vtype: 1,
      vList: [],
      depts: [],
      player: null,
      playerArr: [],
      permission: {
        add: ['admin', 'device:add'],
        edit: ['admin', 'device:edit'],
        del: ['admin', 'device:del']
      },
      rules: {
        no: [
          { required: true, message: '设备编号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '设备名称不能为空', trigger: 'blur' }
        ],
        'dept.id': [
          { required: true, message: '所属公司不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '设备类型不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'name', display_name: '设备名称' }
      ]
    }
  },
  mounted() {},
  beforeDestroy() {
    this.destroyFlv();
  },
  methods: {
    play(n, row) {
      this.vShow = true;
      this.vtype = n;
      this.playerArr=[];
      this.vList = [];
      if(n==2) {//视频
        this.videoList(row.no);
      } else {//直播
        this.initFlv(row.no);
      }

    },
    videoList(no) {
      deviceVideo(no).then(res=>{
        this.vList = res.content;
        setTimeout(()=>{
          this.vList.map(i=>{
            this.initFlv(i.deviceNo, i.id, i.deviceVideoId)
          });
        })
      })
    },
    close() {
      this.vShow = false;
      this.destroyFlv();
    },
    initFlv(no, ele, id) {
      let videoElement = document.getElementById('videoElement');
      let url = `http://223.84.153.141:19080/live/${no}.flv`;
      if(ele) videoElement = document.getElementById('v'+ele);
      if(id) url = `http://223.84.153.141:8000/uploadfile/${no+'-'+id}.flv`;
      // http://223.84.153.141:8000/uploadfile/test17-1706756043.flv
      let flvPlayer = flvjs.createPlayer({
          type: 'flv',
          url
      });
      flvPlayer.attachMediaElement(videoElement);
      flvPlayer.load();
      flvPlayer.play();
      this.player = flvPlayer;
      this.playerArr.push(flvPlayer);
      // 加载完成
      flvPlayer.on(flvjs.Events.LOADING_COMPLETE, (r) => {
        this.$message.warning('链接无效')
      });
      flvPlayer.on(
        flvjs.Events.ERROR,
        (errorType, errorDetail, errorInfo) => {
          this.$message.error('flv资源无效, 播放失败');
          // console.log("errorType", errorType);
          // console.log("errorDetail", errorDetail);
          // console.log("errorInfo", errorInfo);
          // 视频出错后销毁重建
          // this.destroyFlv();
        }
      );
    },
    destroyFlv() {
      if (this.player && this.vtype==1) {
        this.player.pause();
        this.player.unload();
        this.player.detachMediaElement();
        this.player.destroy();
        this.player = null;
      };
      if(this.playerArr.length && this.vtype == 2) {
        this.playerArr.map(i=>{
          i && i.destroy();
        })
      };
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getDeptsList()      
    },
    getDeptsList() {
      getDeptsAll({ enabled: true }).then(res => {
        this.depts = res.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }
  }
}
</script>
<style scoped>
.vBox {
  display: flex;
  flex-wrap: wrap;
}
.vv {
  width: 260px;
  height: 200px;
  margin: 0 10px 20px 0;
  border: 1px solid #000;
}
</style>